<template>
  <div class="todo-today todo-page">
    <div class="todo-today-container todo-page-container">
      <div class="header">
        <div class="left-action">
          <div class="expand">
            <!-- <i class="ri-menu-unfold-3-line"></i> -->
            <!-- <i class="ri-menu-unfold-4-line"></i> -->
          </div>
          <div class="title">{{ todoGroupName }}</div>
        </div>
        <div class="right-action">
          <div class="more">
            <!-- <i class="ri-more-2-line"></i> -->
          </div>
        </div>
      </div>
      <div class="add-task">
        <input
          @keydown.enter="store.handleAddTodo($event, '收集箱')"
          type="text"
          placeholder="＋ 添加任务"
        />
        <div class="action">
          <div class="more">
            <i class="ri-arrow-down-s-line"></i>
          </div>
          <div class="date">
            <i class="ri-time-line"></i>
          </div>
        </div>
      </div>
      <div class="container">
        <div v-if="store.getTodoGroupCount('今天')" class="task-list">
          <div
            :class="`task-group ${todoGroup.groupName}`"
            v-for="todoGroup in todoGroupList"
            v-show="todoGroup.todoList.length"
            :key="todoGroup.groupName"
          >
            <div
              :class="todoGroup.expand ? 'expand expanded' : 'expand'"
              @click="store.handleTodoExpand(todoGroup)"
              v-show="todoGroup.todoList.length"
            >
              <i class="ri-arrow-down-s-line"></i>
              <div class="text">{{ todoGroup.groupName ? todoGroup.groupName : '今天' }}</div>
              <div class="count">{{ todoGroup.todoList.length }}</div>
            </div>
            <div :class="todoGroup.expand ? 'task-list-container show' : 'task-list-container'">
              <div
                @click="handleTodoItemClick(item)"
                @contextmenu="showRightMenu($event, item)"
                class="task-item"
                v-for="item in todoGroup.todoList"
                :key="item.id"
              >
                <CheckBox
                  @click="handleTodoDoneToggle(item)"
                  class="checkbox"
                  v-model:checked="item.isDone"
                ></CheckBox>
                <input
                  @blur="handleTitleInputBlur(item)"
                  @keydown.enter="handleTitleInputEnter($event, item)"
                  type="text"
                  v-model="item.title"
                  placeholder="无标题"
                />
                <div class="task-item-right">
                  <a @click="handleNavTo($event, '/collect')" class="box">
                    <span>收集箱</span>
                  </a>
                  <DatePicker
                    @change="handleDateChange($event, item)"
                    @click.stop
                    :value="dayjs(item.deadlineDate)"
                    :format="customFormat"
                    :class="
                      dayjs(item.deadlineDate).isBefore(dayjs(), 'day')
                        ? 'is-expired date-picker todo-date-picker'
                        : 'date-picker todo-date-picker'
                    "
                    placeholder=""
                    :allow-clear="false"
                  >
                    <template #suffixIcon> </template>
                  </DatePicker>
                </div>
              </div>
            </div>
          </div>
        </div>
        <Empty v-else text="✨祝你有个愉快的一天✨" title="今天没有任务" :icon="emptyIcon"></Empty>
      </div>
    </div>
    <TodoContent @is-done-toggle="handleTodoDoneToggle"></TodoContent>
    <TodoRightMenu
      :menus="rightMenus"
      @action="handleMenuAction"
      ref="todoRightMenuRef"
    ></TodoRightMenu>
  </div>
</template>

<script setup lang="ts">
import CheckBox from '@renderer/components/CheckBox.vue'
import TodoContent from '@renderer/views/TodoContent.vue'
import todoStore from '@renderer/store/todo'
import Empty from '@renderer/components/Empty.vue'
import emptyIcon from '@renderer/assets/icon/app/暂无记录.png'
import { DatePicker } from 'ant-design-vue'
import { TASKGROUP_PATH_MAP } from '@renderer/const'
import { ref, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { sortByDate } from '@renderer/utils'
import dayjs from 'dayjs'
import TodoRightMenu from '@renderer/components/rightMenu/TodoRightMenu.vue'

const store = todoStore()

const route = useRoute()

const router = useRouter()

const currentTodoItem = ref<TodoItem>()

const todoRightMenuRef = ref()

const todoGroupName = ref<string>('')

const todoGroupList = ref<TodoGroup[]>([])

const rightMenus = [
  {
    name: '删除',
    icon: 'ri-delete-bin-5-line',
    action: 'delete'
  },
  {
    name: '完成',
    icon: 'ri-checkbox-circle-line',
    action: 'complete'
  }
]

const getTodoDataList = async () => {
  todoGroupList.value = []
  todoGroupName.value = TASKGROUP_PATH_MAP[route.path]
  const dataList = store.todoList.filter((item) => {
    return (
      item.group === '收集箱' &&
      (dayjs(item.deadlineDate).isSame(dayjs(), 'day') ||
        dayjs(item.doneDate).isSame(dayjs(), 'day'))
    )
  })
  const doneList = dataList.filter((item) => item.isDone)
  const todoList = dataList.filter(
    (item) => !item.isDone && dayjs(item.deadlineDate).isSame(dayjs(), 'day')
  )

  sortByDate(todoList)
  sortByDate(doneList)

  const doneGroup = {
    todoList: doneList,
    groupName: '已完成',
    todoGroupName: '收集箱',
    expand: store.getGroupExpand(route.path, '已完成'),
    path: route.path
  }
  const todoGroup = {
    todoList: todoList,
    groupName: '今天',
    todoGroupName: '收集箱',
    expand: store.getGroupExpand(route.path, '今天'),
    path: route.path
  }

  todoGroupList.value.push(todoGroup, doneGroup)
}

watch(
  () => store.todoList.length,
  () => {
    getTodoDataList()
  }
)

onMounted(() => {
  getTodoDataList()
})

const handleDateChange = (date: any, item: TodoItem) => {
  item.deadlineDate = date
    .toDate()
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    })
    .replace(/\//g, '-')
  window.api.updateTodoData({
    ...item
  })
  getTodoDataList()
}

const customFormat = (value) => {
  const today = dayjs().startOf('day')
  const targetDate = value.startOf('day')
  const diffDays = targetDate.diff(today, 'day')

  if (diffDays === 0) {
    return `今天`
  }
  return `${value.format('M月D日')}`
}

const handleNavTo = (e: Event, path: string) => {
  e.preventDefault()
  e.stopPropagation()
  router.push({
    path
  })
}

const handleTodoItemClick = (todoItem: TodoItem) => {
  store.todo = todoItem
}

const handleTitleInputEnter = (e: KeyboardEvent, todoItem: TodoItem) => {
  if (e.isComposing) {
    return
  }
  window.api.updateTodoData({ ...todoItem })
}

const handleTitleInputBlur = (todoItem: TodoItem) => {
  window.api.updateTodoData({ ...todoItem })
}

const handleTodoDoneToggle = (todoItem: TodoItem) => {
  if (todoItem.isDone) {
    todoItem.doneDate = dayjs().format('YYYY-MM-DD HH:mm:ss')
  } else {
    todoItem.doneDate = ''
  }
  window.api.updateTodoData({
    ...todoItem
  })
  getTodoDataList()
}

const showRightMenu = (e: MouseEvent, todoItem: TodoItem) => {
  e.preventDefault()
  e.stopPropagation()
  currentTodoItem.value = todoItem
  if (todoRightMenuRef.value) {
    todoRightMenuRef.value.showMenu(e)
  }
}

const handleMenuAction = (action: string) => {
  if (!currentTodoItem.value) return
  switch (action) {
    case 'delete':
      // 删除当前任务项
      store.handleDeleteTodo(currentTodoItem.value.id)
      break
    case 'complete':
      // 切换完成状态
      currentTodoItem.value.isDone = !currentTodoItem.value.isDone
      handleTodoDoneToggle(currentTodoItem.value)
      break
    default:
      break
  }
}
</script>

<style scoped></style>
